package hot100;

public class Lc21 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null && list2 == null) return null;
        if (list1 == null) return list2;
        if (list2 == null) return list1;

        ListNode head = null;
        ListNode cur = null;
        while (list1 != null && list2 != null) {
            int val;
            if (list1.val < list2.val) {
                val = list1.val;
                list1 = list1.next;
            }
            else {
                val = list2.val;
                list2 = list2.next;
            }
            if (head == null) {
                head = new ListNode(val);
                cur = head;
            }
            else {
                cur.next = new ListNode(val);
                cur = cur.next;
            }
        }

        ListNode rev = list1 == null ? list2 : list1;
        while (rev != null) {
            int val = rev.val;
            rev = rev.next;
            cur.next = new ListNode(val);
            cur = cur.next;
        }
        return head;
    }
}
